// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <map>
#include <string>

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"
#include "coin2/exchange/base/feed_util/kline.h"

namespace impl {

using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;
using coin2::exchange::base::feed::FeedUpdateManager;

class FtxCommonFeedUpdateParser {
 public:
  static void ParseSnapshot(BookBuilder* book_builder_, const rapidjson::Value& book_json) {
    int64_t timestamp = std::llround(stod(book_json["time"].GetString()) * 1'000'000'000LL);
    auto tx = book_builder_->NewTransaction(timestamp);
    tx.Clear();

    for (const auto& ask : book_json["asks"].GetArray()) {
      double price = stod(ask[0].GetString());
      double size = stod(ask[1].GetString());
      tx.UpdateAsk(price, size);
    }

    for (const auto& bid : book_json["bids"].GetArray()) {
      double price = stod(bid[0].GetString());
      double size = stod(bid[1].GetString());
      tx.UpdateBid(price, size);
    }
  }

  static void ParseUpdate(BookBuilder* book_builder_, const rapidjson::Value& book_json) {
    int64_t timestamp = std::llround(stod(book_json["time"].GetString()) * 1'000'000'000LL);
    auto tx = book_builder_->NewTransaction(timestamp);

    for (const auto& ask : book_json["asks"].GetArray()) {
      double price = stod(ask[0].GetString());
      double size = stod(ask[1].GetString());
      tx.UpdateAsk(price, size);
    }

    for (const auto& bid : book_json["bids"].GetArray()) {
      double price = stod(bid[0].GetString());
      double size = stod(bid[1].GetString());
      tx.UpdateBid(price, size);
    }
  }

  static void ParseBbo(BookBuilder* book_builder_, const rapidjson::Value& book_json) {
    int64_t timestamp = std::llround(stod(book_json["time"].GetString()) * 1'000'000'000LL);
    auto tx = book_builder_->NewTransaction(timestamp);
    tx.Clear();
    if (!book_json["ask"].IsNull()) {
      tx.UpdateAsk(stod(book_json["ask"].GetString()), stod(book_json["askSize"].GetString()));
    }
    if (!book_json["bid"].IsNull()) {
      tx.UpdateBid(stod(book_json["bid"].GetString()), stod(book_json["bidSize"].GetString()));
    }
  }

  static void ParseTrade(const rapidjson::Value& trade_json, Trade* trade) {
    trade->price = stod(trade_json["price"].GetString());
    trade->fill_qty = stod(trade_json["size"].GetString());
    trade->side = ParseTradeSide(trade_json["side"].GetString());
    trade->timestamp = TimestampFromFtxIso8601(trade_json["time"].GetString());
  }

  static coin2::exchange::feed::TradeSide ParseTradeSide(const std::string& side) {
    if (side == "buy") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "sell") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else if (side.empty()) {
      return coin2::exchange::feed::TRADE_NO_SIDE;
    } else {
      throw std::runtime_error("[Ftx Futures] unknown side: " + side);
    }
  }

  static bool ParseKline(
      const rapidjson::Value& kline_json,
      Klines* klines,
      int64_t timestamp,
      fastfeed::proto::KlineInterval interval) {
    int64_t open_timestamp = TimestampFromOkexIso8601(kline_json["startTime"].GetString());
    auto result = klines->AddKline(open_timestamp);
    if (!result) return false;

    Kline* kline;
    bool freezed;
    std::tie(kline, freezed) = result.value();

    kline->open_timestamp = open_timestamp;
    kline->open = stod(kline_json["open"].GetString());
    kline->high = stod(kline_json["high"].GetString());
    kline->low = stod(kline_json["low"].GetString());
    kline->close = stod(kline_json["close"].GetString());
    kline->turnover = stod(kline_json["volume"].GetString());
    kline->volume = kline->turnover / kline->close;
    kline->timestamp = timestamp;
    kline->interval = interval;
    return freezed;
  }

  static fastfeed::proto::KlineInterval ParseKlineInterval(std::string_view period) {
    static std::map<std::string, fastfeed::proto::KlineInterval> interval_map = {
      {"60", fastfeed::proto::KLINE_INTERVAL_1MIN},
      {"180", fastfeed::proto::KLINE_INTERVAL_3MIN},
      {"300", fastfeed::proto::KLINE_INTERVAL_5MIN},
      {"900", fastfeed::proto::KLINE_INTERVAL_15MIN},
      {"1800", fastfeed::proto::KLINE_INTERVAL_30MIN},
      {"3600", fastfeed::proto::KLINE_INTERVAL_1HOUR},
      {"14400", fastfeed::proto::KLINE_INTERVAL_4HOUR},
      {"86400", fastfeed::proto::KLINE_INTERVAL_1DAY},
      {"604800", fastfeed::proto::KLINE_INTERVAL_1WEEK}
    };
    auto iter = interval_map.find(std::string(period));
    if (iter == interval_map.end()) {
      NOTREACHED() << "Not support interval " << period;
      return fastfeed::proto::KLINE_INTERVAL_INVALID;
    }

    return iter->second;
  }
};
}  // namespace impl

using impl::FtxCommonFeedUpdateParser;
